<template>
  <BeModal class="source-table-modal" v-model:open="showModal" centered width="600px" title="批量录入" @ok="onOk" confirmText="保存" customClose :showFooter="false">
    <div class="source-table-modal-body">
      <a-row>
        <a-col :span="24">
          <a-form :model="formState" name="validate_other" v-bind="formItemLayout">
            <a-form-item label="" style="font-size: 24px">
              <a-form-item name="dragger" noStyle>
                <div class="upload-title">
                  <div class="upload-title-left">
                    <div class="upload-title-label">上传文件</div>
                    <div class="upload-title-tip">（文件大小：<1MB, 文件类型:.xlsx、.xls,表格中的数据不支持表达式 ）</div>
                  </div>
                  <div class="upload-title-right">下载模板</div>
                </div>
                <a-upload-dragger
                  v-model:fileList="fileList"
                  :accept="'.xlsx,.xls'"
                  :auto-upload="false"
                  name="file"
                  :maxCount="1"
                  :multiple="false"
                  :beforeUpload="beforeUpload"
                  :headers="uploadHeaders"
                  @drop="handleDrop"
                >
                  <p class="ant-upload-drag-icon">
                    <InboxOutlined />
                  </p>
                  <p class="ant-upload-text">点击或将文件拖拽到这里上传</p>
                </a-upload-dragger>
              </a-form-item>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="24" class="upload-result">
          <div class="upload-title">
            <div class="upload-title-left">
              <div class="upload-title-label">上传结果</div>
            </div>
          </div>
          <div>
            <a-textarea v-model:value="uploadResult" :rows="4" disabled />
          </div>
        </a-col>
      </a-row>
    </div>
  </BeModal>
</template>
<script setup lang="ts">
import { dmsMaskCenterApi } from '@/api/dms-mask-center'
import { reactive, ref } from 'vue'
import { InboxOutlined, DownloadOutlined, BookFilled } from '@ant-design/icons-vue'
import type { UploadChangeParam, UploadFile } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { useUserStoreWithOut } from '@/stores/modules/user'

// emits
const emit = defineEmits(['update:open', 'ok'])
interface Props {
  open?: boolean // 是否打开弹窗
}

// props
const props = withDefaults(defineProps<Props>(), {
  open: false
})
// state
const showModal = ref(false) // 是否显示数据库选择弹窗
// 文件列表和上传状态管理
const fileList = ref<UploadFile[]>([])
const uploadResult = ref('')
// 处理显示
const handleOpen = () => {
  showModal.value = true
}

// 处理关闭
const handleClose = () => {
  showModal.value = false
}

watch(
  () => props.open,
  (val) => {
    fileList.value = []
    showModal.value = val
  }
)

watch(
  () => showModal.value,
  (val) => {
    fileList.value = []
    emit('update:open', val)
  }
)

// 上传前校验
const beforeUpload = (file: UploadFile) => {
  console.log('文件上传前校验：', file)
  // 检查文件数量
  if (fileList.value.length >= 1) {
    message.warning('只能上传一个文件，请先删除已上传的文件！')
    return false
  }

  // 检查文件类型
  const allowedTypes = ['xlsx', 'xls']
  const fileExt = file.name.split('.').pop()?.toLowerCase() || ''
  if (!allowedTypes.includes(fileExt)) {
    message.warning(`不支持的文件类型：.${fileExt}`)
    return false
  }

  // 检查文件大小（最大1GB）
  const maxSize = 1024 * 1024
  if (file.size! > maxSize) {
    message.warning('文件大小不能超过1MB')
    return false
  }
  fileList.value = [file]
  return false
}

function handleDrop(e: DragEvent) {
  console.log(e)
}

const formItemLayout = {
  layout: 'vertical',
  labelCol: { span: 6 },
  wrapperCol: { span: 24 }
}

// 请求头
const uploadHeaders = {
  Authorization: `Bearer ${useUserStoreWithOut().getToken()}`
}

// 处理确定按钮点击
const onOk = () => {
  if (fileList.value.length <= 0) {
    message.error('请先完成文件上传！')
    showModal.value = true
    return false
  }

  // const formData = new FormData()
  // // 2. 添加表单数据（键名需与后端接口参数一致）
  // formData.append('file', fileList.value[0])
  // formData.append('fileEncoding', 'UTF-8')

  // dmsMaskCenterApi
  //   .postTraceability({
  //     data: formData, // 直接传入FormData对象
  //     headers: {
  //       // 显式指定内容类型为multipart/form-data（部分http工具需要）
  //       'Content-Type': 'multipart/form-data'
  //     }
  //   })
  //   .then((response) => {})
  //   .catch((error) => {})
}
defineExpose({ open: handleOpen, close: handleClose })
</script>
<style lang="scss">
.source-table-modal {
  .ant-modal-body {
    // height: calc(100vh - 321px);
    padding: 0;
  }
  &.be-modal--fullscreen {
    .ant-modal-body {
      height: calc(100vh - 121px);
    }
  }
  &-body {
    // flex-direction: column;
    height: 100%;
    padding: 10px;
  }
}
.toolbox-left {
  padding-top: 9rem;
  border-right: solid 1px #f0f0f0;
}
.toolbox-right {
  // display: flex;
  // align-items: center;
  // justify-content: center;
  // height: 100vh;
  // text-align: center;
}

.upload-title {
  display: flex;
  align-items: center;
  font-size: 14px;
  justify-content: space-between;
  margin-bottom: 7px;
  .upload-title-left {
    display: flex;
    align-items: center;
    .upload-title-label {
      color: #000;
      font-weight: bold;
    }
    .upload-title-tip {
      font-size: 12px;
      color: #787676;
    }
  }
  .upload-title-right {
    cursor: pointer;
    color: var(--primary);
    font-weight: bold;
  }
}
.upload-result {
  margin-top: 10px;
}
.ant-form {
  .ant-form-item {
    margin-bottom: 0px !important;
  }
}
.source-table-modal-body {
  padding: 24px;
}
</style>
